import React from 'react';
import { makeAutoObservable } from 'mobx';
import { Router, LoginS } from '../interface/index';
const Login = React.lazy(() => import('../pages/views/Login'));
const Home = React.lazy(() => import('../pages/views/Home'));
const Error = React.lazy(() => import('../pages/views/Error'));
import { loginApi } from '../api/loginApi';


//默认路由
const defaultRouter: Router.RouterProp[] = [
  {
    path: '/',
    element: <Login></Login>,
  },
  {
    path: '/login',
    element: <Login></Login>,
  },
  {
    path: '/home',
    element: <Home></Home>,
  },
  {
    path: '*',
    element: <Error></Error>,
  },
];

const newRouter = defaultRouter.map((item) => item);
//判断你当前登录没有
//如果登录了我就把该有的子路由信息也要装到 home 里面去
if (JSON.parse(sessionStorage.getItem('routerData') as string)) {
  //代表登录过
  let routerData = JSON.parse(sessionStorage.getItem('routerData') as string);
  let children = routerData.map((item: any) => {
    if (!item.children) {
      return {
        path: item.path,
        element: toElement(item.element),
      };
    }
    let c1 = item.children.map((i: any) => {
      return {
        path: i.path,
        element: toElement2(item.element, i.element),
      };
    })
    return {
      path: item.path,
      element: toElement(item.element),
      children: c1
    }
  });
  // console.log('children', children);
  // console.log('children[1].children[0].element', children[1].children[0].element);


  newRouter[2].children = [
    {
      path: '',
      element: children[0].element,
    }, ...children];
}

//将字符串转成对应的组件
function toElement(ele: string | number) {
  const Element = React.lazy(() => import(`../pages/menuPage/${(ele as string).toLowerCase()}/${ele}.tsx`));

  return <Element />;
}
function toElement2(ele: string, val: string) {
  const Element = React.lazy(() => import(`../pages/menuPage/${(ele as string).toLowerCase()}/${val}.tsx`));

  return <Element />;
}



function createStore() {
  return makeAutoObservable({
    routerList: newRouter, //用来放路由信息的
    userInfo:{
      emplId:0,
      emplName:'',
      emplNumber:'',
      roleName:''
    },
    //actions
    //登录
    async login(values: LoginS.loginData) {
      let res = await loginApi(values);
      if(~~res.code !== 200){
        return Promise.resolve({
          status: false,
          msg:res.msg,
          path:'/'
        })
      }
      const {data} = res
      this.userInfo.emplId = data.menus.emplId
      this.userInfo.roleName = data.menus.roleName
      this.userInfo.emplName = data.menus.emplName
      this.userInfo.emplNumber = data.menus.emplNumber
      sessionStorage.setItem('userInfo', JSON.stringify(this.userInfo));
      let oneLevel = data.menus.menus.filter((item:any)=>{
        if(item.pid === 0) return true
        return false
      })
      let towLevel = data.menus.menus.filter((item:any)=>{
        if(item.pid === 0) return false
        return true
      })
      let routerData = oneLevel.map((item1:any)=>{
        let routerDataItem :Router.RouterCache ={
          path:'',
          element:''
        }
        routerDataItem.path = item1.menuUrl
        routerDataItem.element = item1.menuName
        routerDataItem.title = item1.menuRemark
        routerDataItem.display = ~~item1.des
        let childrenRouter =  towLevel.filter((item2:any)=>{
          if(item1.menuId === item2.pid) return true
          return false
        })
        if(childrenRouter){
          childrenRouter = childrenRouter.map((item:any)=>{
            let obj :Router.RouterCache = {
              path:'',
              element:''
            }
            obj.path = item.menuUrl
            obj.element = item.menuName
            obj.title = item.menuRemark
            obj.display = ~~item.des
            return obj
          })
          routerDataItem.children =childrenRouter
        }
        return routerDataItem
      })
      sessionStorage.setItem('token', data.token);
      sessionStorage.setItem('routerData', JSON.stringify(routerData));
      //渲染路由，往 home 里面加children
      let children = routerData.map((item: any) => {
        if (!item.children) {
          return {
            path: item.path,
            element: toElement(item.element),
          };
        }
        let c1 = item.children.map((i: any) => {
          return {
            path: i.path,
            element: toElement2(item.element, i.element),
          };
        })
        return {
          path: item.path,
          element: toElement(item.element),
          children: c1
        }
      });

      let newList = this.routerList;
      newList[2].children = [...children]
      this.routerList = newList;
      //跳转页面
      return Promise.resolve({
        status:true,
        msg:'去吧，皮卡丘！',
        path:children[0].children[0].path
      });
    },

    //退出登录
    logout() {
      sessionStorage.removeItem('token');
      sessionStorage.removeItem('routerData');
      this.routerList = defaultRouter;
    },
  });
}

let store = createStore();

export default store;
